{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "X6bUy2rgmhX6"
   },
   "source": [
    "# AI Health & Fitness Agent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "I76pVPuhmi15"
   },
   "source": [
    "* An AI-powered health and fitness agent that provides personalized dietary and exercise recommendations based on user profiles.\n",
    "* The agent creates customized meal plans, workout routines, and wellness advice considering age, weight, height, activity level, and fitness goals.\n",
    "* Features include dietary preference support (vegetarian, keto, gluten-free), fitness goal targeting (weight loss, muscle gain, endurance), and comprehensive health planning with nutritional guidance."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UBmUqUofoVrf"
   },
   "source": [
    "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/ai_health_fitness_agent.ipynb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Lec7_lpPmyCN"
   },
   "source": [
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "2V2-mVThmzCB"
   },
   "outputs": [],
   "source": [
    "!pip install praisonai streamlit google-generativeai pandas numpy matplotlib seaborn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "McBiobcZnC3W"
   },
   "source": [
    "# Setup Key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "o4Zc-Tv5nD-O",
    "outputId": "d757c1be-dd80-479e-ad97-66867d04f841"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ API key configured!\n",
      "✅ Using model: gemini-2.0-flash-exp\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# Set your Gemini API key\n",
    "gemini_key = \"Enter your api key here\"  # Get from https://aistudio.google.com/apikey\n",
    "\n",
    "# Set environment variable\n",
    "os.environ[\"GOOGLE_API_KEY\"] = gemini_key\n",
    "\n",
    "# Model selection\n",
    "model_choice = \"gemini-2.0-flash-exp\"  # Options: \"gemini-2.0-flash-exp\", \"gemini-1.5-pro\", \"gemini-1.5-flash\"\n",
    "\n",
    "print(\"✅ API key configured!\")\n",
    "print(f\"✅ Using model: {model_choice}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iQtsDCSanTWM"
   },
   "source": [
    "# Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "hQqSszq6nVX-"
   },
   "outputs": [],
   "source": [
    "import math\n",
    "from typing import Dict, Any, List\n",
    "\n",
    "class BMICalculatorTool:\n",
    "    def __init__(self):\n",
    "        self.bmi_categories = {\n",
    "            \"Underweight\": (0, 18.5),\n",
    "            \"Normal weight\": (18.5, 25),\n",
    "            \"Overweight\": (25, 30),\n",
    "            \"Obese\": (30, float('inf'))\n",
    "        }\n",
    "\n",
    "    def calculate_bmi(self, weight_kg: float, height_cm: float) -> Dict[str, Any]:\n",
    "        \"\"\"Calculate BMI and provide health insights\"\"\"\n",
    "        try:\n",
    "            # Convert height from cm to meters\n",
    "            height_m = height_cm / 100\n",
    "\n",
    "            # Calculate BMI\n",
    "            bmi = weight_kg / (height_m ** 2)\n",
    "\n",
    "            # Determine category\n",
    "            category = \"Unknown\"\n",
    "            for cat, (min_val, max_val) in self.bmi_categories.items():\n",
    "                if min_val <= bmi < max_val:\n",
    "                    category = cat\n",
    "                    break\n",
    "\n",
    "            # Calculate ideal weight range\n",
    "            min_ideal_weight = 18.5 * (height_m ** 2)\n",
    "            max_ideal_weight = 25 * (height_m ** 2)\n",
    "\n",
    "            # Health recommendations based on BMI\n",
    "            recommendations = self._get_bmi_recommendations(bmi, category)\n",
    "\n",
    "            return {\n",
    "                \"success\": True,\n",
    "                \"bmi\": round(bmi, 2),\n",
    "                \"category\": category,\n",
    "                \"ideal_weight_range\": {\n",
    "                    \"min\": round(min_ideal_weight, 1),\n",
    "                    \"max\": round(max_ideal_weight, 1)\n",
    "                },\n",
    "                \"recommendations\": recommendations,\n",
    "                \"health_risks\": self._get_health_risks(category)\n",
    "            }\n",
    "        except Exception as e:\n",
    "            return {\"error\": f\"Error calculating BMI: {str(e)}\"}\n",
    "\n",
    "    def _get_bmi_recommendations(self, bmi: float, category: str) -> List[str]:\n",
    "        \"\"\"Get health recommendations based on BMI\"\"\"\n",
    "        recommendations = []\n",
    "\n",
    "        if category == \"Underweight\":\n",
    "            recommendations = [\n",
    "                \"Increase caloric intake with nutrient-dense foods\",\n",
    "                \"Include protein-rich foods in every meal\",\n",
    "                \"Consider strength training to build muscle mass\",\n",
    "                \"Eat frequent, smaller meals throughout the day\"\n",
    "            ]\n",
    "        elif category == \"Normal weight\":\n",
    "            recommendations = [\n",
    "                \"Maintain current healthy eating habits\",\n",
    "                \"Continue regular physical activity\",\n",
    "                \"Focus on balanced nutrition\",\n",
    "                \"Monitor weight regularly\"\n",
    "            ]\n",
    "        elif category == \"Overweight\":\n",
    "            recommendations = [\n",
    "                \"Create a moderate caloric deficit\",\n",
    "                \"Increase physical activity\",\n",
    "                \"Focus on whole foods and vegetables\",\n",
    "                \"Consider working with a nutritionist\"\n",
    "            ]\n",
    "        elif category == \"Obese\":\n",
    "            recommendations = [\n",
    "                \"Consult with healthcare professionals\",\n",
    "                \"Start with low-impact exercises\",\n",
    "                \"Focus on sustainable lifestyle changes\",\n",
    "                \"Consider medical weight loss programs\"\n",
    "            ]\n",
    "\n",
    "        return recommendations\n",
    "\n",
    "    def _get_health_risks(self, category: str) -> List[str]:\n",
    "        \"\"\"Get health risks associated with BMI category\"\"\"\n",
    "        risks = {\n",
    "            \"Underweight\": [\n",
    "                \"Weakened immune system\",\n",
    "                \"Nutritional deficiencies\",\n",
    "                \"Osteoporosis risk\",\n",
    "                \"Reduced muscle mass\"\n",
    "            ],\n",
    "            \"Normal weight\": [\n",
    "                \"Lower risk of chronic diseases\",\n",
    "                \"Better overall health outcomes\"\n",
    "            ],\n",
    "            \"Overweight\": [\n",
    "                \"Increased risk of type 2 diabetes\",\n",
    "                \"Higher blood pressure\",\n",
    "                \"Heart disease risk\",\n",
    "                \"Joint problems\"\n",
    "            ],\n",
    "            \"Obese\": [\n",
    "                \"High risk of cardiovascular disease\",\n",
    "                \"Type 2 diabetes\",\n",
    "                \"Sleep apnea\",\n",
    "                \"Joint and mobility issues\"\n",
    "            ]\n",
    "        }\n",
    "        return risks.get(category, [])\n",
    "\n",
    "# Custom Calorie Calculator Tool\n",
    "class CalorieCalculatorTool:\n",
    "    def __init__(self):\n",
    "        self.activity_multipliers = {\n",
    "            \"Sedentary\": 1.2,\n",
    "            \"Lightly Active\": 1.375,\n",
    "            \"Moderately Active\": 1.55,\n",
    "            \"Very Active\": 1.725,\n",
    "            \"Extremely Active\": 1.9\n",
    "        }\n",
    "\n",
    "    def calculate_calories(self, age: int, weight_kg: float, height_cm: float,\n",
    "                          sex: str, activity_level: str, goal: str) -> Dict[str, Any]:\n",
    "        \"\"\"Calculate daily calorie needs based on goals\"\"\"\n",
    "        try:\n",
    "            # Calculate BMR using Mifflin-St Jeor Equation\n",
    "            if sex.lower() == \"male\":\n",
    "                bmr = 10 * weight_kg + 6.25 * height_cm - 5 * age + 5\n",
    "            else:\n",
    "                bmr = 10 * weight_kg + 6.25 * height_cm - 5 * age - 161\n",
    "\n",
    "            # Calculate TDEE (Total Daily Energy Expenditure)\n",
    "            activity_multiplier = self.activity_multipliers.get(activity_level, 1.2)\n",
    "            tdee = bmr * activity_multiplier\n",
    "\n",
    "            # Adjust calories based on goal\n",
    "            goal_adjustments = {\n",
    "                \"Lose Weight\": -500,  # 500 calorie deficit\n",
    "                \"Gain Muscle\": 300,   # 300 calorie surplus\n",
    "                \"Maintain\": 0,        # No change\n",
    "                \"Endurance\": 200,     # Small surplus for energy\n",
    "                \"Strength Training\": 250  # Moderate surplus\n",
    "            }\n",
    "\n",
    "            calorie_adjustment = goal_adjustments.get(goal, 0)\n",
    "            target_calories = tdee + calorie_adjustment\n",
    "\n",
    "            # Calculate macronutrient breakdown\n",
    "            macros = self._calculate_macros(target_calories, goal)\n",
    "\n",
    "            return {\n",
    "                \"success\": True,\n",
    "                \"bmr\": round(bmr),\n",
    "                \"tdee\": round(tdee),\n",
    "                \"target_calories\": round(target_calories),\n",
    "                \"calorie_adjustment\": calorie_adjustment,\n",
    "                \"macros\": macros,\n",
    "                \"meal_distribution\": self._get_meal_distribution(target_calories)\n",
    "            }\n",
    "        except Exception as e:\n",
    "            return {\"error\": f\"Error calculating calories: {str(e)}\"}\n",
    "\n",
    "    def _calculate_macros(self, calories: float, goal: str) -> Dict[str, Any]:\n",
    "        \"\"\"Calculate macronutrient breakdown\"\"\"\n",
    "        if goal == \"Lose Weight\":\n",
    "            protein_pct = 0.35  # Higher protein for satiety\n",
    "            fat_pct = 0.30\n",
    "            carb_pct = 0.35\n",
    "        elif goal == \"Gain Muscle\":\n",
    "            protein_pct = 0.30\n",
    "            fat_pct = 0.25\n",
    "            carb_pct = 0.45  # Higher carbs for energy\n",
    "        else:  # Maintain or other goals\n",
    "            protein_pct = 0.25\n",
    "            fat_pct = 0.30\n",
    "            carb_pct = 0.45\n",
    "\n",
    "        protein_cals = calories * protein_pct\n",
    "        fat_cals = calories * fat_pct\n",
    "        carb_cals = calories * carb_pct\n",
    "\n",
    "        return {\n",
    "            \"protein\": {\n",
    "                \"calories\": round(protein_cals),\n",
    "                \"grams\": round(protein_cals / 4),\n",
    "                \"percentage\": protein_pct * 100\n",
    "            },\n",
    "            \"fat\": {\n",
    "                \"calories\": round(fat_cals),\n",
    "                \"grams\": round(fat_cals / 9),\n",
    "                \"percentage\": fat_pct * 100\n",
    "            },\n",
    "            \"carbs\": {\n",
    "                \"calories\": round(carb_cals),\n",
    "                \"grams\": round(carb_cals / 4),\n",
    "                \"percentage\": carb_pct * 100\n",
    "            }\n",
    "        }\n",
    "\n",
    "    def _get_meal_distribution(self, total_calories: float) -> Dict[str, int]:\n",
    "        \"\"\"Get calorie distribution across meals\"\"\"\n",
    "        return {\n",
    "            \"breakfast\": round(total_calories * 0.25),\n",
    "            \"lunch\": round(total_calories * 0.30),\n",
    "            \"dinner\": round(total_calories * 0.30),\n",
    "            \"snacks\": round(total_calories * 0.15)\n",
    "        }\n",
    "\n",
    "# Custom Exercise Recommendation Tool\n",
    "class ExerciseRecommendationTool:\n",
    "    def __init__(self):\n",
    "        self.exercise_database = {\n",
    "            \"strength\": {\n",
    "                \"beginner\": [\"Push-ups\", \"Squats\", \"Planks\", \"Lunges\", \"Wall sits\"],\n",
    "                \"intermediate\": [\"Dumbbell rows\", \"Deadlifts\", \"Bench press\", \"Pull-ups\", \"Dips\"],\n",
    "                \"advanced\": [\"Barbell squats\", \"Overhead press\", \"Power cleans\", \"Muscle-ups\", \"Handstand push-ups\"]\n",
    "            },\n",
    "            \"cardio\": {\n",
    "                \"beginner\": [\"Walking\", \"Cycling\", \"Swimming\", \"Elliptical\", \"Light jogging\"],\n",
    "                \"intermediate\": [\"Running\", \"HIIT\", \"Rowing\", \"Jump rope\", \"Stair climbing\"],\n",
    "                \"advanced\": [\"Sprint intervals\", \"Mountain biking\", \"CrossFit\", \"Boxing\", \"Rock climbing\"]\n",
    "            },\n",
    "            \"flexibility\": {\n",
    "                \"beginner\": [\"Static stretching\", \"Yoga basics\", \"Foam rolling\", \"Cat-cow stretches\", \"Child's pose\"],\n",
    "                \"intermediate\": [\"Dynamic stretching\", \"Vinyasa yoga\", \"Pilates\", \"Hip openers\", \"Shoulder mobility\"],\n",
    "                \"advanced\": [\"Advanced yoga poses\", \"Contortion\", \"Gymnastics\", \"Dance\", \"Martial arts\"]\n",
    "            }\n",
    "        }\n",
    "\n",
    "    def get_exercise_plan(self, goal: str, fitness_level: str,\n",
    "                         available_time: int, equipment: List[str]) -> Dict[str, Any]:\n",
    "        \"\"\"Generate personalized exercise plan\"\"\"\n",
    "        try:\n",
    "            # Determine exercise focus based on goal\n",
    "            if goal == \"Lose Weight\":\n",
    "                focus = [\"cardio\", \"strength\"]\n",
    "                cardio_ratio = 0.6\n",
    "            elif goal == \"Gain Muscle\":\n",
    "                focus = [\"strength\", \"cardio\"]\n",
    "                cardio_ratio = 0.3\n",
    "            elif goal == \"Endurance\":\n",
    "                focus = [\"cardio\", \"strength\"]\n",
    "                cardio_ratio = 0.7\n",
    "            elif goal == \"Strength Training\":\n",
    "                focus = [\"strength\", \"flexibility\"]\n",
    "                cardio_ratio = 0.2\n",
    "            else:  # Stay Fit\n",
    "                focus = [\"strength\", \"cardio\", \"flexibility\"]\n",
    "                cardio_ratio = 0.4\n",
    "\n",
    "            # Generate workout plan\n",
    "            workout_plan = {\n",
    "                \"warm_up\": self._get_warmup_routine(fitness_level),\n",
    "                \"main_workout\": self._get_main_workout(focus, fitness_level, available_time, cardio_ratio),\n",
    "                \"cool_down\": self._get_cooldown_routine(fitness_level),\n",
    "                \"frequency\": self._get_workout_frequency(goal, fitness_level),\n",
    "                \"progression\": self._get_progression_plan(fitness_level, goal)\n",
    "            }\n",
    "\n",
    "            return {\n",
    "                \"success\": True,\n",
    "                \"goal\": goal,\n",
    "                \"fitness_level\": fitness_level,\n",
    "                \"workout_plan\": workout_plan,\n",
    "                \"tips\": self._get_exercise_tips(goal, fitness_level)\n",
    "            }\n",
    "        except Exception as e:\n",
    "            return {\"error\": f\"Error generating exercise plan: {str(e)}\"}\n",
    "\n",
    "    def _get_warmup_routine(self, fitness_level: str) -> List[str]:\n",
    "        \"\"\"Get appropriate warmup routine\"\"\"\n",
    "        warmups = {\n",
    "            \"beginner\": [\n",
    "                \"5-10 minutes light walking or cycling\",\n",
    "                \"Arm circles (10 forward, 10 backward)\",\n",
    "                \"Leg swings (10 each leg)\",\n",
    "                \"Gentle stretching\"\n",
    "            ],\n",
    "            \"intermediate\": [\n",
    "                \"5-10 minutes dynamic warmup\",\n",
    "                \"Jumping jacks (30 seconds)\",\n",
    "                \"High knees (30 seconds)\",\n",
    "                \"Butt kicks (30 seconds)\",\n",
    "                \"Arm and leg mobility exercises\"\n",
    "            ],\n",
    "            \"advanced\": [\n",
    "                \"10-15 minutes dynamic warmup\",\n",
    "                \"Jump rope (2-3 minutes)\",\n",
    "                \"Burpees (5-10 reps)\",\n",
    "                \"Mountain climbers (30 seconds)\",\n",
    "                \"Full body mobility routine\"\n",
    "            ]\n",
    "        }\n",
    "        return warmups.get(fitness_level, warmups[\"beginner\"])\n",
    "\n",
    "    def _get_main_workout(self, focus: List[str], fitness_level: str,\n",
    "                         available_time: int, cardio_ratio: float) -> Dict[str, Any]:\n",
    "        \"\"\"Generate main workout based on focus and time\"\"\"\n",
    "        workout = {}\n",
    "\n",
    "        # Calculate time allocation\n",
    "        cardio_time = int(available_time * cardio_ratio)\n",
    "        strength_time = available_time - cardio_time\n",
    "\n",
    "        if \"cardio\" in focus:\n",
    "            workout[\"cardio\"] = {\n",
    "                \"duration\": cardio_time,\n",
    "                \"exercises\": self.exercise_database[\"cardio\"][fitness_level][:3],\n",
    "                \"intensity\": \"Moderate to High\" if fitness_level != \"beginner\" else \"Low to Moderate\"\n",
    "            }\n",
    "\n",
    "        if \"strength\" in focus:\n",
    "            workout[\"strength\"] = {\n",
    "                \"duration\": strength_time,\n",
    "                \"exercises\": self.exercise_database[\"strength\"][fitness_level][:4],\n",
    "                \"sets\": 3 if fitness_level != \"beginner\" else 2,\n",
    "                \"reps\": \"8-12\" if fitness_level != \"beginner\" else \"10-15\"\n",
    "            }\n",
    "\n",
    "        if \"flexibility\" in focus:\n",
    "            workout[\"flexibility\"] = {\n",
    "                \"duration\": 10,\n",
    "                \"exercises\": self.exercise_database[\"flexibility\"][fitness_level][:3]\n",
    "            }\n",
    "\n",
    "        return workout\n",
    "\n",
    "    def _get_cooldown_routine(self, fitness_level: str) -> List[str]:\n",
    "        \"\"\"Get cooldown routine\"\"\"\n",
    "        cooldowns = {\n",
    "            \"beginner\": [\n",
    "                \"5 minutes light walking\",\n",
    "                \"Gentle stretching\",\n",
    "                \"Deep breathing exercises\"\n",
    "            ],\n",
    "            \"intermediate\": [\n",
    "                \"5-10 minutes light activity\",\n",
    "                \"Static stretching\",\n",
    "                \"Foam rolling\"\n",
    "            ],\n",
    "            \"advanced\": [\n",
    "                \"10 minutes light activity\",\n",
    "                \"Comprehensive stretching\",\n",
    "                \"Recovery techniques\"\n",
    "            ]\n",
    "        }\n",
    "        return cooldowns.get(fitness_level, cooldowns[\"beginner\"])\n",
    "\n",
    "    def _get_workout_frequency(self, goal: str, fitness_level: str) -> Dict[str, Any]:\n",
    "        \"\"\"Get recommended workout frequency\"\"\"\n",
    "        if goal == \"Lose Weight\":\n",
    "            frequency = 4 if fitness_level != \"beginner\" else 3\n",
    "        elif goal == \"Gain Muscle\":\n",
    "            frequency = 4 if fitness_level != \"beginner\" else 3\n",
    "        elif goal == \"Endurance\":\n",
    "            frequency = 5 if fitness_level != \"beginner\" else 4\n",
    "        else:\n",
    "            frequency = 3\n",
    "\n",
    "        return {\n",
    "            \"workouts_per_week\": frequency,\n",
    "            \"rest_days\": 7 - frequency,\n",
    "            \"recommendation\": f\"Work out {frequency} times per week with {7-frequency} rest days\"\n",
    "        }\n",
    "\n",
    "    def _get_progression_plan(self, fitness_level: str, goal: str) -> List[str]:\n",
    "        \"\"\"Get progression recommendations\"\"\"\n",
    "        if fitness_level == \"beginner\":\n",
    "            return [\n",
    "                \"Start with 2-3 workouts per week\",\n",
    "                \"Focus on proper form and technique\",\n",
    "                \"Gradually increase intensity over 4-6 weeks\",\n",
    "                \"Consider working with a trainer initially\"\n",
    "            ]\n",
    "        elif fitness_level == \"intermediate\":\n",
    "            return [\n",
    "                \"Increase workout frequency to 4-5 times per week\",\n",
    "                \"Add more challenging exercises\",\n",
    "                \"Incorporate progressive overload\",\n",
    "                \"Consider periodization training\"\n",
    "            ]\n",
    "        else:  # advanced\n",
    "            return [\n",
    "                \"Maintain 5-6 workouts per week\",\n",
    "                \"Focus on specific skill development\",\n",
    "                \"Incorporate advanced training techniques\",\n",
    "                \"Consider competition or performance goals\"\n",
    "            ]\n",
    "\n",
    "    def _get_exercise_tips(self, goal: str, fitness_level: str) -> List[str]:\n",
    "        \"\"\"Get exercise-specific tips\"\"\"\n",
    "        tips = [\n",
    "            \"Always warm up before exercising\",\n",
    "            \"Listen to your body and rest when needed\",\n",
    "            \"Stay hydrated throughout your workout\",\n",
    "            \"Focus on proper form over weight or speed\"\n",
    "        ]\n",
    "\n",
    "        if goal == \"Lose Weight\":\n",
    "            tips.extend([\n",
    "                \"Combine cardio and strength training\",\n",
    "                \"Keep workouts consistent\",\n",
    "                \"Monitor your heart rate during cardio\"\n",
    "            ])\n",
    "        elif goal == \"Gain Muscle\":\n",
    "            tips.extend([\n",
    "                \"Progressive overload is key\",\n",
    "                \"Allow adequate rest between sets\",\n",
    "                \"Focus on compound movements\"\n",
    "            ])\n",
    "\n",
    "        return tips"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8X5bHKSxngCY"
   },
   "source": [
    "# YAML Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "gPb_ZcIhnign",
    "outputId": "d8e29f5f-19e8-4cbf-8105-1a8749102635"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ YAML Prompt configured!\n"
     ]
    }
   ],
   "source": [
    "# YAML Prompt\n",
    "yaml_prompt = \"\"\"\n",
    "name: \"AI Health & Fitness Agent\"\n",
    "description: \"Expert health and fitness advisor with personalized planning capabilities\"\n",
    "instructions:\n",
    "  - \"You are an expert health and fitness advisor that creates personalized plans based on user profiles\"\n",
    "  - \"Consider user's age, weight, height, activity level, and fitness goals when making recommendations\"\n",
    "  - \"Provide safe, evidence-based advice for diet and exercise\"\n",
    "  - \"Create detailed meal plans with nutritional information and calorie counts\"\n",
    "  - \"Design workout routines appropriate for the user's fitness level and goals\"\n",
    "  - \"Always prioritize safety and recommend consulting healthcare professionals when appropriate\"\n",
    "  - \"Provide clear explanations for why specific recommendations are made\"\n",
    "  - \"Consider dietary restrictions and preferences in meal planning\"\n",
    "  - \"Include progression plans and tips for long-term success\"\n",
    "\n",
    "tools:\n",
    "  - name: \"BMICalculatorTool\"\n",
    "    description: \"Calculates BMI, provides health insights, and generates weight management recommendations\"\n",
    "  - name: \"CalorieCalculatorTool\"\n",
    "    description: \"Calculates daily calorie needs, macronutrient breakdown, and meal distribution based on goals\"\n",
    "  - name: \"ExerciseRecommendationTool\"\n",
    "    description: \"Generates personalized exercise plans with warm-up, main workout, and cool-down routines\"\n",
    "\n",
    "output_format:\n",
    "  - \"Provide comprehensive health assessments with BMI and calorie calculations\"\n",
    "  - \"Include detailed meal plans with nutritional breakdown\"\n",
    "  - \"Offer personalized exercise routines with proper progression\"\n",
    "  - \"Include safety considerations and professional consultation advice\"\n",
    "  - \"Provide actionable tips and long-term success strategies\"\n",
    "  - \"Use clear, structured formatting with sections for diet and fitness\"\n",
    "\n",
    "temperature: 0.3\n",
    "max_tokens: 4000\n",
    "model: \"gemini-2.0-flash-exp\"\n",
    "\"\"\"\n",
    "\n",
    "print(\"✅ YAML Prompt configured!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "VGYwIdNhnmcx"
   },
   "source": [
    "# Main"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "-NVyHi8CnnmC",
    "outputId": "89b46c46-b1a9-4fb4-cdb3-318b1b375f2e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🏋️‍♂️ AI Health & Fitness Agent\n",
      "Get personalized health and fitness plans tailored to your goals!\n",
      "\n",
      "👤 Your Health Profile\n",
      "Please provide your information:\n",
      "Age: 25\n",
      "Weight (kg): 43\n",
      "Height (cm): 152\n",
      "Sex (Male/Female/Other): Female\n",
      "Activity Level (Sedentary/Lightly Active/Moderately Active/Very Active/Extremely Active): Lightly Active\n",
      "Fitness Goals (Lose Weight/Gain Muscle/Endurance/Stay Fit/Strength Training): Gain Muscle\n",
      "Dietary Preferences (Vegetarian/Keto/Gluten Free/Low Carb/Dairy Free/None): None\n",
      "\n",
      "✅ Profile created for 25-year-old Female with Gain Muscle goals\n",
      "\n",
      "📊 Health Assessment\n",
      "Calculating BMI and health metrics...\n",
      "✅ BMI: 18.61 (Normal weight)\n",
      "�� Ideal weight range: 42.7 - 57.8 kg\n",
      "\n",
      "💡 Health Recommendations:\n",
      "  - Maintain current healthy eating habits\n",
      "  - Continue regular physical activity\n",
      "  - Focus on balanced nutrition\n",
      "  - Monitor weight regularly\n",
      "\n",
      "⚠️ Health Risks:\n",
      "  - Lower risk of chronic diseases\n",
      "  - Better overall health outcomes\n",
      "\n",
      "🔥 Calorie Analysis\n",
      "Calculating daily calorie needs...\n",
      "✅ BMR (Basal Metabolic Rate): 1094 calories/day\n",
      "✅ TDEE (Total Daily Energy Expenditure): 1504 calories/day\n",
      "�� Target Calories: 1804 calories/day\n",
      "\n",
      "🍽️ Macronutrient Breakdown:\n",
      "  Protein: 135g (30.0%)\n",
      "  Fat: 50g (25.0%)\n",
      "  Carbs: 203g (45.0%)\n",
      "\n",
      "⏰ Meal Distribution:\n",
      "  Breakfast: 451 calories\n",
      "  Lunch: 541 calories\n",
      "  Dinner: 541 calories\n",
      "  Snacks: 271 calories\n",
      "\n",
      "💪 Exercise Plan\n",
      "Generating personalized workout routine...\n",
      "✅ Fitness Level: beginner\n",
      "🎯 Goal: Gain Muscle\n",
      "\n",
      "🔥 Warm-up Routine:\n",
      "  - 5-10 minutes light walking or cycling\n",
      "  - Arm circles (10 forward, 10 backward)\n",
      "  - Leg swings (10 each leg)\n",
      "  - Gentle stretching\n",
      "\n",
      "🏋️‍♂️ Main Workout:\n",
      "  Cardio (18 minutes):\n",
      "    - Walking\n",
      "    - Cycling\n",
      "    - Swimming\n",
      "  Strength Training (42 minutes):\n",
      "    - Push-ups (2 sets, 10-15 reps)\n",
      "    - Squats (2 sets, 10-15 reps)\n",
      "    - Planks (2 sets, 10-15 reps)\n",
      "    - Lunges (2 sets, 10-15 reps)\n",
      "\n",
      "🧘‍♀️ Cool-down Routine:\n",
      "  - 5 minutes light walking\n",
      "  - Gentle stretching\n",
      "  - Deep breathing exercises\n",
      "\n",
      "�� Workout Frequency: Work out 3 times per week with 4 rest days\n",
      "\n",
      "💡 Exercise Tips:\n",
      "  - Always warm up before exercising\n",
      "  - Listen to your body and rest when needed\n",
      "  - Stay hydrated throughout your workout\n",
      "  - Focus on proper form over weight or speed\n",
      "  - Progressive overload is key\n",
      "  - Allow adequate rest between sets\n",
      "  - Focus on compound movements\n",
      "\n",
      "📈 Progression Plan:\n",
      "  - Start with 2-3 workouts per week\n",
      "  - Focus on proper form and technique\n",
      "  - Gradually increase intensity over 4-6 weeks\n",
      "  - Consider working with a trainer initially\n",
      "\n",
      "🎯 Personalized Recommendations\n",
      "\n",
      "🍽️ Dietary Recommendations:\n",
      "  - Ensure adequate protein intake (1.6-2.2g per kg body weight)\n",
      "  - Include complex carbohydrates for energy\n",
      "  - Don't forget healthy fats\n",
      "  - Consider protein timing around workouts\n",
      "\n",
      "⚠️ Important Safety Considerations:\n",
      "  - Consult with a healthcare professional before starting any new diet or exercise program\n",
      "  - Start slowly and gradually increase intensity\n",
      "  - Listen to your body and rest when needed\n",
      "  - Stay hydrated and maintain proper nutrition\n",
      "  - Consider working with certified trainers or nutritionists\n",
      "\n",
      "📊 Progress Tracking Recommendations:\n",
      "  - Track your weight weekly (same time, same conditions)\n",
      "  - Take progress photos monthly\n",
      "  - Keep a food and exercise journal\n",
      "  - Monitor energy levels and mood\n",
      "  - Set realistic, measurable goals\n",
      "\n",
      "🍽️ Sample Meal Plan (1 Day):\n",
      "Based on your calorie target and preferences\n",
      "\n",
      "🌅 Breakfast (451 calories):\n",
      "  - Scrambled eggs with spinach\n",
      "  - Whole grain toast\n",
      "  - Fresh fruit\n",
      "\n",
      "🌞 Lunch (541 calories):\n",
      "  - Quinoa bowl with vegetables\n",
      "  - Lean protein (chicken/fish/tofu)\n",
      "  - Healthy dressing\n",
      "\n",
      "🌙 Dinner (541 calories):\n",
      "  - Lean protein with vegetables\n",
      "  - Complex carbohydrates\n",
      "  - Healthy fats\n",
      "\n",
      "�� Snacks (271 calories):\n",
      "  - Fresh fruit or vegetables\n",
      "  - Nuts or seeds\n",
      "  - Greek yogurt or cottage cheese\n",
      "\n",
      "==================================================\n",
      "🏋️‍♂️ Powered by AI Health & Fitness Agent | Built with PraisonAI\n",
      "💡 Remember: Consistency is key to achieving your health and fitness goals!\n"
     ]
    }
   ],
   "source": [
    "# Main Application (Google Colab Version)\n",
    "import streamlit as st\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from typing import Dict, Any, List\n",
    "import os\n",
    "\n",
    "# Initialize tools\n",
    "bmi_tool = BMICalculatorTool()\n",
    "calorie_tool = CalorieCalculatorTool()\n",
    "exercise_tool = ExerciseRecommendationTool()\n",
    "\n",
    "print(\"🏋️‍♂️ AI Health & Fitness Agent\")\n",
    "print(\"Get personalized health and fitness plans tailored to your goals!\")\n",
    "\n",
    "# User profile input\n",
    "print(\"\\n👤 Your Health Profile\")\n",
    "print(\"Please provide your information:\")\n",
    "\n",
    "# Get user input\n",
    "age = int(input(\"Age: \"))\n",
    "weight = float(input(\"Weight (kg): \"))\n",
    "height = float(input(\"Height (cm): \"))\n",
    "sex = input(\"Sex (Male/Female/Other): \")\n",
    "activity_level = input(\"Activity Level (Sedentary/Lightly Active/Moderately Active/Very Active/Extremely Active): \")\n",
    "fitness_goals = input(\"Fitness Goals (Lose Weight/Gain Muscle/Endurance/Stay Fit/Strength Training): \")\n",
    "dietary_preferences = input(\"Dietary Preferences (Vegetarian/Keto/Gluten Free/Low Carb/Dairy Free/None): \")\n",
    "\n",
    "print(f\"\\n✅ Profile created for {age}-year-old {sex} with {fitness_goals} goals\")\n",
    "\n",
    "# Health Assessment\n",
    "print(\"\\n📊 Health Assessment\")\n",
    "print(\"Calculating BMI and health metrics...\")\n",
    "\n",
    "bmi_result = bmi_tool.calculate_bmi(weight, height)\n",
    "if \"error\" not in bmi_result:\n",
    "    print(f\"✅ BMI: {bmi_result['bmi']} ({bmi_result['category']})\")\n",
    "    print(f\"�� Ideal weight range: {bmi_result['ideal_weight_range']['min']} - {bmi_result['ideal_weight_range']['max']} kg\")\n",
    "\n",
    "    print(\"\\n💡 Health Recommendations:\")\n",
    "    for rec in bmi_result['recommendations']:\n",
    "        print(f\"  - {rec}\")\n",
    "\n",
    "    print(\"\\n⚠️ Health Risks:\")\n",
    "    for risk in bmi_result['health_risks']:\n",
    "        print(f\"  - {risk}\")\n",
    "else:\n",
    "    print(f\"❌ Error calculating BMI: {bmi_result['error']}\")\n",
    "\n",
    "# Calorie Calculation\n",
    "print(\"\\n🔥 Calorie Analysis\")\n",
    "print(\"Calculating daily calorie needs...\")\n",
    "\n",
    "calorie_result = calorie_tool.calculate_calories(\n",
    "    age, weight, height, sex, activity_level, fitness_goals\n",
    ")\n",
    "\n",
    "if \"error\" not in calorie_result:\n",
    "    print(f\"✅ BMR (Basal Metabolic Rate): {calorie_result['bmr']} calories/day\")\n",
    "    print(f\"✅ TDEE (Total Daily Energy Expenditure): {calorie_result['tdee']} calories/day\")\n",
    "    print(f\"�� Target Calories: {calorie_result['target_calories']} calories/day\")\n",
    "\n",
    "    print(\"\\n🍽️ Macronutrient Breakdown:\")\n",
    "    macros = calorie_result['macros']\n",
    "    print(f\"  Protein: {macros['protein']['grams']}g ({macros['protein']['percentage']}%)\")\n",
    "    print(f\"  Fat: {macros['fat']['grams']}g ({macros['fat']['percentage']}%)\")\n",
    "    print(f\"  Carbs: {macros['carbs']['grams']}g ({macros['carbs']['percentage']}%)\")\n",
    "\n",
    "    print(\"\\n⏰ Meal Distribution:\")\n",
    "    meals = calorie_result['meal_distribution']\n",
    "    print(f\"  Breakfast: {meals['breakfast']} calories\")\n",
    "    print(f\"  Lunch: {meals['lunch']} calories\")\n",
    "    print(f\"  Dinner: {meals['dinner']} calories\")\n",
    "    print(f\"  Snacks: {meals['snacks']} calories\")\n",
    "else:\n",
    "    print(f\"❌ Error calculating calories: {calorie_result['error']}\")\n",
    "\n",
    "# Exercise Plan\n",
    "print(\"\\n💪 Exercise Plan\")\n",
    "print(\"Generating personalized workout routine...\")\n",
    "\n",
    "# Determine fitness level based on activity level\n",
    "fitness_level_map = {\n",
    "    \"Sedentary\": \"beginner\",\n",
    "    \"Lightly Active\": \"beginner\",\n",
    "    \"Moderately Active\": \"intermediate\",\n",
    "    \"Very Active\": \"intermediate\",\n",
    "    \"Extremely Active\": \"advanced\"\n",
    "}\n",
    "fitness_level = fitness_level_map.get(activity_level, \"intermediate\")\n",
    "\n",
    "exercise_result = exercise_tool.get_exercise_plan(\n",
    "    fitness_goals, fitness_level, 60, [\"bodyweight\", \"dumbbells\"]\n",
    ")\n",
    "\n",
    "if \"error\" not in exercise_result:\n",
    "    print(f\"✅ Fitness Level: {fitness_level}\")\n",
    "    print(f\"🎯 Goal: {fitness_goals}\")\n",
    "\n",
    "    workout_plan = exercise_result['workout_plan']\n",
    "\n",
    "    print(\"\\n🔥 Warm-up Routine:\")\n",
    "    for warmup in workout_plan['warm_up']:\n",
    "        print(f\"  - {warmup}\")\n",
    "\n",
    "    print(\"\\n🏋️‍♂️ Main Workout:\")\n",
    "    main_workout = workout_plan['main_workout']\n",
    "\n",
    "    if 'cardio' in main_workout:\n",
    "        cardio = main_workout['cardio']\n",
    "        print(f\"  Cardio ({cardio['duration']} minutes):\")\n",
    "        for exercise in cardio['exercises']:\n",
    "            print(f\"    - {exercise}\")\n",
    "\n",
    "    if 'strength' in main_workout:\n",
    "        strength = main_workout['strength']\n",
    "        print(f\"  Strength Training ({strength['duration']} minutes):\")\n",
    "        for exercise in strength['exercises']:\n",
    "            print(f\"    - {exercise} ({strength['sets']} sets, {strength['reps']} reps)\")\n",
    "\n",
    "    if 'flexibility' in main_workout:\n",
    "        flexibility = main_workout['flexibility']\n",
    "        print(f\"  Flexibility ({flexibility['duration']} minutes):\")\n",
    "        for exercise in flexibility['exercises']:\n",
    "            print(f\"    - {exercise}\")\n",
    "\n",
    "    print(\"\\n🧘‍♀️ Cool-down Routine:\")\n",
    "    for cooldown in workout_plan['cool_down']:\n",
    "        print(f\"  - {cooldown}\")\n",
    "\n",
    "    print(f\"\\n�� Workout Frequency: {workout_plan['frequency']['recommendation']}\")\n",
    "\n",
    "    print(\"\\n💡 Exercise Tips:\")\n",
    "    for tip in exercise_result['tips']:\n",
    "        print(f\"  - {tip}\")\n",
    "\n",
    "    print(\"\\n📈 Progression Plan:\")\n",
    "    for progression in workout_plan['progression']:\n",
    "        print(f\"  - {progression}\")\n",
    "else:\n",
    "    print(f\"❌ Error generating exercise plan: {exercise_result['error']}\")\n",
    "\n",
    "# Personalized Recommendations\n",
    "print(\"\\n🎯 Personalized Recommendations\")\n",
    "\n",
    "# Dietary recommendations based on goals and preferences\n",
    "print(\"\\n🍽️ Dietary Recommendations:\")\n",
    "if fitness_goals == \"Lose Weight\":\n",
    "    print(\"  - Create a moderate caloric deficit\")\n",
    "    print(\"  - Focus on high-protein foods for satiety\")\n",
    "    print(\"  - Include plenty of vegetables and fiber\")\n",
    "    print(\"  - Stay hydrated with water\")\n",
    "elif fitness_goals == \"Gain Muscle\":\n",
    "    print(\"  - Ensure adequate protein intake (1.6-2.2g per kg body weight)\")\n",
    "    print(\"  - Include complex carbohydrates for energy\")\n",
    "    print(\"  - Don't forget healthy fats\")\n",
    "    print(\"  - Consider protein timing around workouts\")\n",
    "elif fitness_goals == \"Endurance\":\n",
    "    print(\"  - Focus on carbohydrates for energy\")\n",
    "    print(\"  - Include moderate protein for recovery\")\n",
    "    print(\"  - Stay well-hydrated\")\n",
    "    print(\"  - Consider sports nutrition for long sessions\")\n",
    "\n",
    "# Dietary preference adjustments\n",
    "if dietary_preferences != \"None\":\n",
    "    print(f\"\\n🥗 {dietary_preferences} Adjustments:\")\n",
    "    if dietary_preferences == \"Vegetarian\":\n",
    "        print(\"  - Include plant-based protein sources (beans, lentils, tofu)\")\n",
    "        print(\"  - Consider B12 supplementation\")\n",
    "        print(\"  - Ensure adequate iron from plant sources\")\n",
    "    elif dietary_preferences == \"Keto\":\n",
    "        print(\"  - Keep carbs under 50g per day\")\n",
    "        print(\"  - Focus on healthy fats and proteins\")\n",
    "        print(\"  - Monitor ketone levels\")\n",
    "    elif dietary_preferences == \"Gluten Free\":\n",
    "        print(\"  - Choose gluten-free grains (quinoa, rice, oats)\")\n",
    "        print(\"  - Read labels carefully\")\n",
    "        print(\"  - Ensure adequate fiber intake\")\n",
    "\n",
    "# Safety and Professional Advice\n",
    "print(\"\\n⚠️ Important Safety Considerations:\")\n",
    "print(\"  - Consult with a healthcare professional before starting any new diet or exercise program\")\n",
    "print(\"  - Start slowly and gradually increase intensity\")\n",
    "print(\"  - Listen to your body and rest when needed\")\n",
    "print(\"  - Stay hydrated and maintain proper nutrition\")\n",
    "print(\"  - Consider working with certified trainers or nutritionists\")\n",
    "\n",
    "# Progress Tracking\n",
    "print(\"\\n📊 Progress Tracking Recommendations:\")\n",
    "print(\"  - Track your weight weekly (same time, same conditions)\")\n",
    "print(\"  - Take progress photos monthly\")\n",
    "print(\"  - Keep a food and exercise journal\")\n",
    "print(\"  - Monitor energy levels and mood\")\n",
    "print(\"  - Set realistic, measurable goals\")\n",
    "\n",
    "# Sample Meal Plan\n",
    "print(\"\\n🍽️ Sample Meal Plan (1 Day):\")\n",
    "print(\"Based on your calorie target and preferences\")\n",
    "\n",
    "if \"target_calories\" in calorie_result:\n",
    "    target_cals = calorie_result['target_calories']\n",
    "    meals = calorie_result['meal_distribution']\n",
    "\n",
    "    print(f\"\\n🌅 Breakfast ({meals['breakfast']} calories):\")\n",
    "    if dietary_preferences == \"Vegetarian\":\n",
    "        print(\"  - Greek yogurt with berries and nuts\")\n",
    "        print(\"  - Whole grain toast with avocado\")\n",
    "        print(\"  - Green tea or coffee\")\n",
    "    else:\n",
    "        print(\"  - Scrambled eggs with spinach\")\n",
    "        print(\"  - Whole grain toast\")\n",
    "        print(\"  - Fresh fruit\")\n",
    "\n",
    "    print(f\"\\n🌞 Lunch ({meals['lunch']} calories):\")\n",
    "    if dietary_preferences == \"Keto\":\n",
    "        print(\"  - Grilled chicken salad with olive oil\")\n",
    "        print(\"  - Mixed greens and vegetables\")\n",
    "        print(\"  - Nuts and seeds\")\n",
    "    else:\n",
    "        print(\"  - Quinoa bowl with vegetables\")\n",
    "        print(\"  - Lean protein (chicken/fish/tofu)\")\n",
    "        print(\"  - Healthy dressing\")\n",
    "\n",
    "    print(f\"\\n🌙 Dinner ({meals['dinner']} calories):\")\n",
    "    print(\"  - Lean protein with vegetables\")\n",
    "    print(\"  - Complex carbohydrates\")\n",
    "    print(\"  - Healthy fats\")\n",
    "\n",
    "    print(f\"\\n�� Snacks ({meals['snacks']} calories):\")\n",
    "    print(\"  - Fresh fruit or vegetables\")\n",
    "    print(\"  - Nuts or seeds\")\n",
    "    print(\"  - Greek yogurt or cottage cheese\")\n",
    "\n",
    "# Footer\n",
    "print(\"\\n\" + \"=\"*50)\n",
    "print(\"🏋️‍♂️ Powered by AI Health & Fitness Agent | Built with PraisonAI\")\n",
    "print(\"💡 Remember: Consistency is key to achieving your health and fitness goals!\")"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
